export const block: ICustomBlockOption = {
    name: "SToyFlame",
    comments: "实现ShaderToy火焰效果",
    document: "https://www.shadertoy.com/view/MdX3zr",
    target: "Neutral",
    inParameters: [
        {
            name: "uv",
            type: "Vector2"
        },
        {
            name: "time",
            type: "Float"
        }
    ],
    outParameters: [
        {
            name: "output",
            type: "Vector4"
        }
    ],
    "includes": [
        "//helperFunctions",
        "shaderToyDeclaration"
    ],
    entryFunctionName: "SToyFlame",
    code: `
        float SToyFlame_noise(vec3 p)
        {
            vec3 i = floor(p);
            vec4 a = dot(i, vec3(1., 57., 21.)) + vec4(0., 57., 21., 78.);
            vec3 f = cos((p-i)*acos(-1.))*(-.5)+.5;
            a = mix(sin(cos(a)*a),sin(cos(1.+a)*(1.+a)), f.x);
            a.xy = mix(a.xz, a.yw, f.y);
            return mix(a.x, a.y, f.z);
        }

        float SToyFlame_sphere(vec3 p, vec4 spr)
        {
            return length(spr.xyz-p) - spr.w;
        }

        float SToyFlame_flame(vec3 p)
        {
            float d = SToyFlame_sphere(p*vec3(1.,.5,1.), vec4(.0,-1.,.0,1.));
            return d + (SToyFlame_noise(p+vec3(.0,iTime*2.,.0)) + SToyFlame_noise(p*3.)*.5)*.25*(p.y) ;
        }

        float SToyFlame_scene(vec3 p)
        {
            return min(100.-length(p) , abs(SToyFlame_flame(p)) );
        }

        vec4 raymarch(vec3 org, vec3 dir)
        {
            float d = 0.0, glow = 0.0, eps = 0.02;
            vec3  p = org;
            bool glowed = false;

            for(int i=0; i<64; i++)
            {
                d = SToyFlame_scene(p) + eps;
                p += d * dir;
                if( d>eps )
                {
                    if(SToyFlame_flame(p) < .0)
                        glowed=true;
                    if(glowed)
                        glow = float(i)/64.;
                }
            }
            return vec4(p,glow);
        }

        void SToyFlame(vec2 fragCoord, float time, out vec4 fragColor)
        {
            iTime = time;
            vec2 v = -1.0 + 2.0 * fragCoord.xy / iResolution.xy;
            v.x *= iResolution.x/iResolution.y;

            vec3 org = vec3(0., -2., 4.);
            vec3 dir = normalize(vec3(v.x*1.6, -v.y, -1.5));

            vec4 p = raymarch(org, dir);
            float glow = p.w;

            vec4 col = mix(vec4(1.,.5,.1,1.), vec4(0.1,.5,1.,1.), p.y*.02+.4);

            fragColor = mix(vec4(0.), col, pow(glow*2.,4.));
        }
    `
}